package com.micai.boss.sms.repository;

import com.micai.boss.base.exception.ServiceException;
import org.springframework.stereotype.Repository;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 描述：
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/4/24 15:01
 */
@Repository
public class TemplateParser {

    private Pattern pattern = Pattern.compile("\\$\\{\\s*[a-z]+[a-zA-Z0-9_]*\\s*\\}");

    public String parse(String templet, Map<String, String> vars) {
        Matcher m = pattern.matcher(templet);
        while (m.find()) {
            // 例子 ${code }
            String s = m.group();
            // 例子 code
            String n = s.substring(s.indexOf('{') + 1, s.indexOf('}'));
            String value = vars.get(n.trim());
            if (value == null) {
                throw new ServiceException("变量没有找到:" + n.trim());
            }
            templet = templet.replace(s, value);
        }
        if (templet.contains("${")) {
            throw new ServiceException("模版解析错误，包含未解析的变量:[" + templet + "] 变量:" + vars);
        }
        return templet;
    }
}
